package com.skaz.util;

import com.google.common.net.HttpHeaders;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Author: jungle
 * @Date: 2019/3/14 3:51 PM
 */
public class Servlets {

    public static void sendFailure(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        Integer status = Exceptions.determineResponseStatus(ex);
        String message = Exceptions.determineResponseMessage(ex);
        sendFailure(request, response, status, message);
    }

    private static void sendFailure(HttpServletRequest request, HttpServletResponse response, Integer status, String message) throws IOException {
        //只针对前后端分离
        sendJsonFailureResult(response, status, message);
    }

    private static void sendJsonFailureResult(HttpServletResponse response, Integer status, String message) throws IOException {
        sendJsonFailureResult(response, null, status, message);
    }

    private static void sendJsonFailureResult(HttpServletResponse response, Map<String, Object> content, Integer status, String message) throws IOException {
        sendJson(response, Results.failureWithData(status, content, message), status);
    }

    private static void sendJson(HttpServletResponse response, Object result, Integer status) throws IOException {
        PrintWriter writer = null;
        try {
            String jsonString = "";
            if (result != null) {
                jsonString = Jsons.toJSONString(result);
            }
            setContentTypeJson(response);
            setNoCacheHeader(response);
            setStatus(response, status);
            writer = response.getWriter();
            writer.write(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            IOUtils.closeQuietly(writer);
        }

    }

    private static void setStatus(HttpServletResponse response, Integer status) {
        response.setStatus(status);
    }

    public static void setContentTypeJson(HttpServletResponse response) {
        setContentType(response, MediaTypes.APPLICATION_JSON_UTF_8);
    }

    public static void setContentType(HttpServletResponse response, String contentType) {
        response.setHeader("Content-Type", contentType);
    }

    /**
     * 设置禁止客户端缓存的Header.
     */
    public static void setNoCacheHeader(HttpServletResponse response) {
        // Http 1.0 header
        response.setDateHeader(HttpHeaders.EXPIRES, 1L);
        response.addHeader(HttpHeaders.PRAGMA, "no-cache");
        // Http 1.1 header
        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0");
    }
}
